<template>
  <pageHeader
    :title="
      route.query.saveId
        ? '修改产品BOM'
        : route.query.historyId
        ? '新增产品BOM版本'
        : '新增产品BOM'
    "
    :breadCrumb="['工厂建模', '产品BOM管理', '产品BOM管理']"
    :show-back="true"
  >
    <template #footer>
      <a-space :size="20">
        <a-button @click="router.back()">取消</a-button>
        <a-button type="primary" @click="handleOk">保存</a-button>
      </a-space>
    </template>
    <a-spin :loading="loading" class="cantainer">
      <div class="tab">产品信息</div>
      <a-form :model="formData" ref="refForm" auto-label-width class="form">
        <a-row :gutter="15">
          <a-col :span="12">
            <a-form-item
              label="关联产品"
              field="productId"
              :rules="getRules('关联产品')"
            >
              <ProductChoice
                @choice="choiceProduct"
                :disabled="!!formData.id || !!route.query.historyId"
                ref="refProductChoice"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="产品编码">
              <a-input
                placeholder="无需输入，自动带入"
                :model-value="formData.management?.number"
                disabled
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="规格型号">
              <a-input
                placeholder="无需输入，自动带入"
                :model-value="formData.management?.spec"
                disabled
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="基本单位">
              <a-input
                placeholder="无需输入，自动带入"
                :model-value="formData.management?.unitData?.name"
                disabled
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="产品属性">
              <a-select
                placeholder="无需输入，自动带入"
                :model-value="formData.management?.attribute"
                disabled
              >
                <a-option :value="1">自制</a-option>
                <a-option :value="2">委外</a-option>
                <a-option :value="3">虚拟</a-option>
                <a-option :value="4">采购</a-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <div class="tab">产品bom信息</div>
      <a-form :model="formData" ref="refForm" auto-label-width class="form">
        <a-row :gutter="15">
          <a-col :span="12">
            <a-form-item label="产品BOM编码">
              <a-input
                placeholder="无需输入，系统自动生成..."
                disabled
                v-model="formData.bomCode"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item
              label="BOM名称"
              field="bomName"
              :rules="getRules('产品BOM名称')"
            >
              <a-input
                v-model="formData.bomName"
                placeholder="请输入产品BOM名称"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item
              label="BOM版本号"
              field="bomEdition"
              :rules="getRules('BOM版本号')"
            >
              <a-input
                v-model="formData.bomEdition"
                placeholder="请输入产品BOM版本号"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item
              label="启用状态"
              field="state"
              :rules="getRules('启用状态')"
            >
              <a-select v-model="formData.state" placeholder="请选择">
                <a-option
                  v-for="(item, index) in ['启用', '停用']"
                  :key="item"
                  :value="index + 1"
                >
                  {{ item }}
                </a-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <div class="tab">产品BOM明细</div>
      <ProductChoice @choice="productBomChoice">
        <a-button type="primary">
          <template #icon>
            <icon-plus />
          </template>
          添加产品BOM
        </a-button>
      </ProductChoice>
      <div class="tab"></div>
      <a-table :data="productBomDetailList" show-empty-tree row-key="uuid">
        <!-- arco-table的插槽，默认为columns -->
        <template #columns>
          <a-table-column
            title="BOM名称"
            :width="200"
            data-index="productBomDetail.bomName"
            align="center"
          />
          <a-table-column
            title="BOM版本号"
            :width="200"
            data-index="productBomDetail.bomEdition"
            align="center"
          />
          <a-table-column
            title="物料编码"
            :width="200"
            data-index="productBomDetail.management.number"
            align="center"
          />
          <a-table-column
            title="物料名称"
            :width="200"
            data-index="productBomDetail.management.name"
            align="center"
          />
          <a-table-column
            title="规格型号"
            :width="200"
            data-index="productBomDetail.management.spec"
            align="center"
          />
          <a-table-column
            title="单位"
            :width="180"
            data-index="productBomDetail.management.unitData.name"
            align="center"
          />

          <!-- <a-table-column :width="130" title="材料属性" align="center">
          <template #cell="{ record }">
            {{
              record.attribute === 1
                ? '自制'
                : record.attribute === 2
                ? '委外'
                : record.attribute === 3
                ? '虚拟'
                : '采购'
            }}
          </template>
        </a-table-column> -->
          <a-table-column :width="130" title="材料属性" align="center">
            <template #cell="{ record }">
              <a-select
                v-model="record.productBomDetail.management.attribute"
                disabled
              >
                <a-option :value="1">自制</a-option>
                <a-option :value="2">委外</a-option>
                <a-option :value="3">虚拟</a-option>
                <a-option :value="4">采购</a-option>
              </a-select>
            </template>
          </a-table-column>

          <a-table-column
            :width="130"
            fixed="right"
            title="标准用量"
            align="center"
          >
            <template #cell="{ record }">
              <a-input-number
                v-model="record.dosage"
                :disabled="record.isSon"
                placeholder="标准用量"
                hide-button
              />
            </template>
          </a-table-column>
          <a-table-column
            :width="130"
            fixed="right"
            title="损耗率"
            align="center"
          >
            <template #cell="{ record }">
              <a-input-number
                v-model="record.wastage"
                :max="100"
                :min="1"
                :disabled="record.isSon"
                hide-button
              >
                <template #suffix> % </template>
              </a-input-number>
            </template>
          </a-table-column>
          <a-table-column :width="80" fixed="right" title="操作" align="center">
            <template #cell="{ rowIndex, record }">
              <a-space v-if="!record.isSon">
                <a-popconfirm
                  content="是否删除该数据?"
                  type="error"
                  @ok="productBomDetailList.splice(rowIndex, 1)"
                >
                  <a-link status="danger"> 删除 </a-link>
                </a-popconfirm>
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-spin>
  </pageHeader>
</template>

<script setup lang="ts">
  import { reactive, onMounted, ref, nextTick } from 'vue';
  import {
    GetProductBom,
    AddProductBom,
    EditProductBom,
    CheckProductBom,
    GetProductBomTree,
    GetProductBomPage,
  } from '@/api/FactoryModeling';
  import uniqueid from 'lodash.uniqueid';
  import { Message } from '@arco-design/web-vue';
  import { useRoute, useRouter } from 'vue-router';
  import { TbomBase, TProductBomDetail } from '@/api/FactoryModeling/type';
  import ProductChoice from '@/views/client-side/FactoryModeling/components/ProductChoice.vue';
  import ProductBomChoice from '@/views/client-side/FactoryModeling/components/ProductBomChoice.vue';

  let route = useRoute();
  let router = useRouter();
  let loading = ref(false);
  let formData = reactive<TbomBase>({
    state: 1,
  });
  let getRules = (name?: string) => {
    return [{ required: true, message: (name || '') + '不能为空' }];
  };
  let productBomDetailList = ref<any[]>([]);
  let refForm = ref();
  let handleOk = async () => {
    try {
      let check = await refForm.value.validate();
      let check2 = productBomDetailList.value.some(({ dosage }, index) => {
        if (!dosage) {
          Message.error('第' + (index + 1) + '条子BOM标准用量未填写');
        }
        return !dosage;
      });
      if (!check && !check2) {
        let data = {
          ...formData,
          productBomDetail: productBomDetailList.value,
        };
        if (formData.id) {
          await EditProductBom({ ...data });
        } else {
          await AddProductBom({
            ...data,
            historyState: route.query.historyId ? 2 : 1,
          });
        }
        router.back();
      }
    } catch (err) {
      console.log(err);
    }
  };
  let refProductChoice = ref();
  let getChildren = async (id: number) => {
    let tree = await GetProductBomTree(id);
    let filterList = (list: any[] | undefined): any[] | undefined => {
      return (
        list?.map((item) => {
          return {
            uuid: uniqueid(''),
            isSon: true,
            ...item,
            children: filterList(item.children),
            productBomDetail: {
              ...item,
              management: { ...item.management },
            },
            management: undefined,
          };
        }) || undefined
      );
    };
    return Promise.resolve(filterList(tree.children));
  };
  onMounted(async () => {
    if (!route.query.saveId && !route.query.copyId && !route.query.historyId)
      return;
    loading.value = true;
    try {
      let res = await GetProductBom({
        id: route.query.saveId || route.query.copyId || route.query.historyId,
      });
      let treeList = await Promise.all(
        res.productBomDetail.map(({ bomId }: any) => getChildren(bomId))
      );
      let data: TbomBase = {
        ...res,
        id: route.query.copyId || route.query.historyId ? undefined : res.id,
        productBomDetail:
          res.productBomDetail.map((item: any, index: number) => {
            return {
              uuid: uniqueid(''),
              ...item,
              children: treeList[index],
              wastage: Number(item.wastage),
              id:
                route.query.copyId || route.query.historyId
                  ? undefined
                  : item.id,
            };
          }) || [],
        productId: route.query.copyId ? undefined : res.productId,
        management: route.query.copyId ? undefined : res.management,
      };
      Object.assign(formData, data);
      productBomDetailList.value = data.productBomDetail || [];
      if (route.query.saveId || route.query.historyId) {
        refProductChoice.value.inputValue = res.management?.name;
      }
      console.log(productBomDetailList.value);
    } catch (err) {
      console.error(err);
    }
    loading.value = false;
  });
  let choiceProduct = async (data: any) => {
    loading.value = true;
    try {
      let res = await CheckProductBom({ productId: data.id });
      if (!res.length) {
        formData.productId = data.id;
        formData.management = {
          ...data,
          material: {
            name: data.basicName,
          },
        };
        if (data.attribute !== 4) {
          formData.bomCode = 'F-' + data.number;
        }
      } else {
        Message.error('该产品已有BOM');
        refProductChoice.value.inputValue = '';
      }
    } catch (err) {
      console.error(err);
    }
    loading.value = false;
  };
  let productBomChoice = async (data: any) => {
    if (data.materialProperty === 4) {
      return productBomDetailList.value.push({
        productId: data.id,
        children: [],
        productBomDetail: {
          management: data,
        },
      });
    }
    if (
      !productBomDetailList.value.every(
        ({ productBomDetail }) => productBomDetail.management.id !== data.id
      )
    ) {
      return Message.error('不可重复添加数据');
    }
    try {
      loading.value = true;
      let { content } = await GetProductBomPage({
        page: 1,
        size: -1,
        historyState: 1,
        productId: data.id,
      });
      if (!content.length) {
        Message.error('选择的产品不是委外且没有BOM，请先定义该产品BOM');
        return (loading.value = false);
      }
      let getBom = await GetProductBom({ id: content[0].id });

      if (!formData.id) {
        productBomDetailList.value.push({
          bomId: getBom.id,
          children: await getChildren(getBom.id),
          productBomDetail: getBom,
        });
        return (loading.value = false);
      }
      let tree = await GetProductBomTree(getBom.id);
      let check = false;
      let ergodicCheck = (list?: any[]) => {
        if (
          list?.some((item) => {
            ergodicCheck(item.children);
            return formData.id === item.id;
          })
        ) {
          check = true;
        }
      };
      ergodicCheck([tree]);
      loading.value = false;
      if (check) {
        Message.error('选择BOM的子项已包含本BOM，请重新选择');
        return (loading.value = false);
      }
      productBomDetailList.value.push({
        bomId: getBom.id,
        children: await getChildren(getBom.id),
        productBomDetail: getBom,
      });
    } catch (err) {
      return (loading.value = false);
    }
  };
</script>

<style scoped lang="less">
  .cantainer {
    padding: 20px;
    width: 100%;
  }
  .tab {
    border-left: 4px rgb(var(--arcoblue-6)) solid;
    padding-left: 20px;
    margin-bottom: 30px;
    font-size: 20px;
  }
  .form {
    padding-left: 50px;
    padding-right: 50px;
  }

  .box {
    padding-top: 10px;
    margin-top: 20px;
    border-top: 1px solid #e4e4e4;
    display: flex;
    justify-content: end;
  }
</style>
